// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.InformationSecurity.ISRM.TaskManagment.Classes;
using Microsoft.InformationSecurity.ISRM.TaskManagment.TaskMessages;
using System.Data;
using System.Data.SqlClient;

namespace Microsoft.InformationSecurity.ISRM.TaskManagment.Classes
{
    /// <summary>
    /// Implements methods to maintain categories in the database.
    /// </summary>
    public static class Categories
    {
        /// <summary>
        /// Adds a category to the database.
        /// </summary>
        /// <param name="category">New Category</param>
        /// <returns>Category ID</returns>
        public static int AddCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            if (string.IsNullOrEmpty(category.Name))
                throw new ArgumentNullException("CategoryName", TaskMessages.Messages.GetServiceMessage("CategoryNameNotNull"));

            ValidationResults validationResults = Validation.Validate<Category>(category, "CategoryBasicRules");

            if (validationResults.IsValid == false)
            {
                throw new ArgumentException(TaskMessages.Messages.GetServiceMessage("CategoryValidationFailed"));
            }
            int categoryID = -1;
            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                SqlCommand createCatCommand = new SqlCommand("ISRM_spInsertTaskCategory");
                createCatCommand.CommandType = CommandType.StoredProcedure;
                createCatCommand.Parameters.Add("@categoryName", SqlDbType.NVarChar, 100);
                createCatCommand.Parameters.Add("@username", SqlDbType.NVarChar, 50);
                createCatCommand.Parameters.Add("@categoryID", SqlDbType.Int);
                createCatCommand.Parameters["@categoryName"].Value = category.Name;
                createCatCommand.Parameters["@username"].Value = category.LastUpdatedBy;
                createCatCommand.Parameters["@categoryID"].Direction = ParameterDirection.Output;
                createCatCommand.Parameters.Add("@personID", SqlDbType.Int).Value = category.PersonID;

                db.ExecuteNonQuery(createCatCommand);
                categoryID = (int)createCatCommand.Parameters["@categoryID"].Value;
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                {
                    db = null;
                }
            }
            return categoryID;
        }


        /// <summary>
        /// Updates a category in the database.
        /// </summary>
        /// <param name="category">Updated Category</param>
        public static void UpdateCategory(Microsoft.InformationSecurity.ISRM.TaskManagment.Classes.Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            if (string.IsNullOrEmpty(category.Name))
                throw new ArgumentNullException("CategoryName", TaskMessages.Messages.GetServiceMessage("CategoryNameNotNull"));

            Validator<Category> categoryValidator = ValidationFactory.CreateValidator<Category>();
            ValidationResults validationResults = categoryValidator.Validate(category);
            if (validationResults.IsValid == false)
            {
                throw new ArgumentException(TaskMessages.Messages.GetServiceMessage("CategoryValidationFailed"));
            }
            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                db.ExecuteNonQuery("ISRM_spUpdateTaskCategory", category.ID, category.Name, category.LastUpdatedBy, category.PersonID);
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                    db = null;
            }
        }

        /// <summary>
        /// Deletes a category from the database.
        /// </summary>
        /// <param name="categoryID">Category ID</param>
        /// <param name="username">Username</param>
        /// <param name="personID">personID</param>
        public static void DeleteCategory(int categoryID, string username, int personID)
        {
            if (categoryID <= 0)
                throw new ArgumentNullException("categoryID");


            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                db.ExecuteNonQuery("ISRM_spDeleteTaskCategory", categoryID, username, personID);
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                    db = null;
            }
        }

        /// <summary>
        /// Returns the list of active categories
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static ICollection<Category> GetActiveCategories()
        {
            Database db = null;
            IDataReader dbReader = null;
            List<Category> lstCategories = new List<Category>();
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                dbReader = (SqlDataReader)db.ExecuteReader(CommandType.StoredProcedure, "ISRM_spGetActiveTaskCategories");
                while (dbReader.Read())
                {
                    Category category = new Category();
                    category.ID = dbReader.GetInt32(0);
                    category.Name = dbReader.GetString(1);
                    category.LastUpdatedBy = dbReader.GetString(2);
                    category.LastUpdatedDate = dbReader.GetDateTime(3);
                    category.TaskCount = dbReader.GetInt32(4);
                    category.Active = true;

                    lstCategories.Add(category);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dbReader != null)
                {
                    dbReader.Close();
                    dbReader = null;
                }
                if (db != null)
                {
                    db = null;
                }
            }
            return lstCategories;
        }

        /// <summary>
        /// Returns the list of active categories
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static ICollection<Category> GetAllCategories()
        {
            Database db = null;
            IDataReader dbReader = null;
            List<Category> lstCategories = new List<Category>();
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                dbReader = (SqlDataReader)db.ExecuteReader(CommandType.StoredProcedure, "ISRM_spGetAllTaskCategories");
                while (dbReader.Read())
                {
                    Category category = new Category();
                    category.ID = dbReader.GetInt32(0);
                    category.Name = dbReader.GetString(1);
                    category.LastUpdatedBy = dbReader.GetString(2);
                    category.LastUpdatedDate = dbReader.GetDateTime(3);
                    category.TaskCount = dbReader.GetInt32(4);
                    category.Active = dbReader.GetBoolean(5);

                    lstCategories.Add(category);
                }
            }
            catch { throw; }
            finally
            {
                if (dbReader != null)
                {
                    dbReader.Close();
                    dbReader = null;
                }
                if (db != null)
                    db = null;
            }
            return lstCategories;
        }
    }
}
